/**
 * 
 */
package com.yzt.insys.control;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yzt.insys.beans.Component;
import com.yzt.insys.beans.Device;
import com.yzt.insys.beans.DeviceComp;
import com.yzt.insys.beans.Oil;
import com.yzt.insys.common.PageNavation;
import com.yzt.insys.service.BigCateService;
import com.yzt.insys.service.CategoryService;
import com.yzt.insys.service.ComponentService;
import com.yzt.insys.service.DeptService;
import com.yzt.insys.service.DetectRecordService;
import com.yzt.insys.service.DeviceService;
import com.yzt.insys.service.OilRecordService;
import com.yzt.insys.service.OilService;
import com.yzt.insys.service.PowerService;
import com.yzt.insys.service.ReplaceRecordService;

/**
 * 创建人:朱顺福<br />
 * 创建日期:2014年7月2日<br />
 * 创建时间:上午12:46:14<br />
 * 说      明:<br />
 */
@Scope("prototype")
@Controller
@RequestMapping("/device")
@SuppressWarnings("unchecked")
public class DeviceControl extends BaseControl {


	@Resource
	@Qualifier("deviceService")
	private DeviceService deviceService;
	
	@Resource
	private DeptService deptService;
	
	@Resource
	private CategoryService categoryService;
	
	@Resource
	private ComponentService componentService;
	
	@Resource
	private OilService oilService;
	
	@Resource
	private PowerService powerService;
	
	@Resource
	private OilRecordService oilRecordService;
	
	@Resource
	private ReplaceRecordService replaceRecordService;
	
	@Resource
	private DetectRecordService detectRecordService;
	
	@Resource
	private BigCateService bigCateService;
	
	//private HttpServletRequest request;
	
	@RequestMapping(value = "/all/{masterName}")
	public synchronized String toAll(@PathVariable("masterName")String masterName) {
		reqAddAttr("powers",powerService.querySubPowerByMasterName(masterName));
		return "menu/device/all";
	}
	
	@ResponseBody
	@RequestMapping(value="/getData",method={RequestMethod.POST,RequestMethod.GET})
	public String getData(PageNavation page){
		List<String> rpList=(List<String>)session.getAttribute("powerKeys");
		paramMap=getParamMap();
		StringBuilder sb=new StringBuilder();
		if(rpList.contains("viewAllDevice")){//如果有查看所有部门设备权限
			paramMap.put("deptId",null);
		}else if(rpList.contains("viewOwnerDevice")){//如果有查看本部门设备权限
			paramMap.put("deptId",getUserFromSession().getDeptId());
		}else{
			sb.append("{\"total\":0,");
			sb.append("\"rows\":[]");
			sb.append("}");
			return sb.toString();
		}
		if(paramMap.get("page")==null){
			paramMap.put("page",1);
		}
		if(paramMap.get("rows")==null){
			paramMap.put("rows",10000);
		}
		page.setParamMap(paramMap);
		page.setCurrentPage(Integer.parseInt(paramMap.get("page").toString()));//获取当前页码
		page.setPageSize(Integer.parseInt(paramMap.get("rows").toString()));//获取每页显示数量
		page.setStartIndex((page.getCurrentPage()-1)*page.getPageSize());//设置查询开始位置
		int totalCount=deviceService.queryModelCount(paramMap);
		sb.append("{\"total\":"+totalCount+",");
		sb.append("\"rows\":");
		List<Device> list=null;
		if(totalCount!=0){
			list=deviceService.queryModelList(page);//获取集合对象			
			sb.append(JSON.toJSONString(list));
		}else{
			sb.append("[]");
		}
		sb.append("}");
		return sb.toString();
	}
	
	@RequestMapping("/toAdd")
	public String toAdd() {
		reqAddAttr("paramMap", getParamMap());
		reqAddAttr("deptList",deptService.queryModelList(getPage()));	
		reqAddAttr("categoryList",categoryService.queryModelList(getPage()));
		reqAddAttr("bigCateList",bigCateService.queryModelList(getPage()));
		return forward_toAdd();
	}
	
	@ResponseBody
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Object add(Device device,String compStr,String oilStr){
		device.setCreatedBy(getUserFromSession().getId());
		boolean flg=deviceService.insert(device);
		List<Component> components=null;
		List<Oil> oilList=null; 
		if(compStr!=null&&compStr.trim().length()>2){
			components=JSON.parseArray(compStr,Component.class);
			paramMap.clear();
			paramMap.put("deviceId",device.getId());
			paramMap.put("createdBy",getUserFromSession().getId());
			paramMap.put("components",components);
			flg=componentService.batchInsert(paramMap);
		}
		if(oilStr!=null&&oilStr.trim().length()>2){
			oilList=JSON.parseArray(oilStr,Oil.class);
			paramMap.clear();
			paramMap.put("deviceId",device.getId());
			paramMap.put("createdBy",getUserFromSession().getId());
			paramMap.put("oilList",oilList);
			flg=oilService.batchInsert(paramMap);
		}
		return flg;
	}
	
	@RequestMapping("/toUpd/{id}")
	public String toUpd(@PathVariable("id") Long id){
		reqAddAttr("paramMap",getParamMap());
		reqAddAttr("categoryList",categoryService.queryModelList(getPage()));
		reqAddAttr("deptList",deptService.queryModelList(getPage()));
		reqAddAttr("device",deviceService.queryByPK(id));
		reqAddAttr("bigCateList",bigCateService.queryModelList(getPage()));
		return forward_toUpd();
	}
	@ResponseBody
	@RequestMapping(value="/upd",method=RequestMethod.POST)
	public Object upd(Device device,String compStr,String oilStr,Integer component,Integer oil){
		device.setCreatedBy(getUserFromSession().getId());
		boolean flg=deviceService.updateByPK(device);
		List<Component> components=null;
		List<Oil> oilList=null;
		paramMap.clear();
		paramMap.put("deviceId",device.getId());
		paramMap.put("createdBy",getUserFromSession().getId());
		paramMap.put("deletedBy",paramMap.get("createdBy"));
		componentService.delDeviceComp(paramMap);
		if(compStr!=null&&compStr.trim().length()>2){
				components=JSON.parseArray(compStr,Component.class);
				paramMap.put("components",components);
				flg=componentService.batchInsert(paramMap);
		}

		oilService.delDeviceOil(paramMap);
		if(oilStr!=null&&oilStr.trim().length()>2){
			oilList=JSON.parseArray(oilStr,Oil.class);
			paramMap.put("oilList",oilList);
			flg=oilService.batchInsert(paramMap);
		}
		return flg;
	}
	
	@ResponseBody
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Object del(@RequestParam("ids")List<Long> ids){
		paramMap=getDeletedMap(ids);
		boolean flg=false;
		flg=deviceService.delete(paramMap);
		/*
		componentService.deleteByDeviceIds(paramMap);
		replaceRecordService.deleteByDeviceIds(paramMap);//删除y_replace_record表中的数据
		detectRecordService.deleteByDeviceIds(paramMap);
		oilService.deleteByDeviceId(paramMap);//删除y_device_oil表中的数据
		componentService.deleteByDeviceIds(paramMap);//删除y_device_comp表中的数据
		List<Long> deviceOilIds=oilService.queryIdsByDeviceIds(paramMap);//获取deviceOilId
		if(deviceOilIds.size()>0){
			paramMap.put("ids",deviceOilIds);				
			oilRecordService.delete(paramMap);//删除y_oil_record表中的数据
		}
		*/
		return flg;
	}
	
	@RequestMapping("/view/{id}")
	public Object view(@PathVariable("id")Long id){
		reqAddAttr("device",deviceService.queryByPK(id));
		return forward_toView();
	}
	
	@ResponseBody
	@RequestMapping(value="/getAllCompByDeviceId")
	public Object getAllCompByDeviceId(Long deviceId,Integer count){
		StringBuffer sb=new StringBuffer();
		if(deviceId==null){
			sb.append("{\"total\":0,");
			sb.append("\"rows\":[]}");
			return sb.toString();
		}
		paramMap.clear();
		paramMap.put("deviceId",deviceId);
		paramMap.put("count",count);
		List<DeviceComp> deviceComps=deviceService.getAllCompByDeviceId(paramMap);
		sb.append("{\"total\":"+deviceComps.size()+",");
		sb.append("\"rows\":");
		if(deviceComps.size()==0){
			sb.append("[]}");
			return sb.toString();
		}
		paramList=new ArrayList<Object>();
		for(DeviceComp dc:deviceComps){
			if(dc!=null){
				paramMap=new HashMap<String,Object>();
				paramMap.put("deviceCompId",dc.getDeviceCompId());
				paramMap.put("name",dc.getComponent().getName());
				paramMap.put("cycle",dc.getComponent().getCycle());
				paramMap.put("count",dc.getComponent().getCount());
				paramMap.put("startDate",dc.getComponent().getStartDate());
				paramList.add(paramMap);
			}
		}
		sb.append(toJSONStringWithDateFormat(paramList,"yyyy-MM-dd")+"}");
		return sb.toString();
	}
	
	@RequestMapping("/index")
	public String index(){
		List<String> rpList=(List<String>)session.getAttribute("powerKeys");
		if(rpList.contains("viewAllDevice")){//如果有查看所有部门设备权限
			paramMap.put("deptId",null);
		}else if(rpList.contains("viewOwnerDevice")){//如果有查看本部门设备权限
			paramMap.put("deptId",getUserFromSession().getDeptId());
		}else{
			return "commons/welcome1";			
		}
		reqAddAttr("expireDetectDevices",deviceService.queryExpireDetect(paramMap));
		reqAddAttr("expireOilDevices",oilRecordService.queryExpireOil(paramMap));
		reqAddAttr("expireReplaceDevices",replaceRecordService.queryExpireReplace(paramMap));
		reqAddAttr("expireCheckDevices",deviceService.queryExpireCheck(paramMap));
		return "commons/welcome1";	
		
	}

	/*@Override
	protected void reqAddAttr(String key, Object value) {
		this.request.setAttribute(key, value);
	}

	@Override
	protected String getViewNameForRequest(HttpServletRequest request) {
		this.request=request;
		return super.getViewNameForRequest(request);
	}*/
	
}
